<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>PK模式</title>
    <link rel="icon" href="/img/dgs.jpg" type="/image/jpg" >
    <link rel="stylesheet" href="/layui/css/layui.css">
    <style>
        #openLayer{
            position: absolute;
            width: 100%;
            height: 100%;
        }

        #openLayerContent{
            width: 300px;
            margin: 0 auto;
        }

        #start{
            padding-top: 15px;
            font-style:italic;
            height:85px;
            width: 350px;
            margin-top: 300px;
            color: #ffc807;
            font-size: 50px;
            text-align: center;
            font-family:'微软雅黑';
            cursor: pointer;
        }

        #leave{
            padding-top: 15px;
            font-style:italic;
            height:85px;
            width: 350px;
            margin-top: 150px;
            color: #fdfcfa;
            font-size: 50px;
            text-align: center;
            font-family:'微软雅黑';
            cursor: pointer;
        }


        #userInformationLayer{
            display: none;
            position: absolute;
            width: 100%;
            height: 100%;
        }

        #userInformationLayerContent{
            width: 1100px;
            height: 700px;
            margin: 100px auto 0;
            border-radius: 50px;
            background: rgba(0,0,0,0.6);
        }

        #userInformationLeftFrame{
            position: absolute;
            width: 250px;
            height: 450px;
            margin: 125px 0 0 50px;
            border-radius: 20px;
            background: rgba(255,255,255,0.8);
        }

        #segmentPositionDv{
            width: 175px;
            height: 175px;
            margin: 20px auto 0;
            border-radius: 100%;
            border: 1px solid red;
        }

        #segmentPositionNumberDv{
            width: 175px;
            margin: 45px auto 0;
            text-align: center;
            font-size: 2em;
        }

        #segmentPositionNameDv{
            width: 175px;
            margin: 10px auto 0;
            text-align: center;
            font-size: 2em;
        }

        #userMatchNumberDv{
            float: left;
            width: 100px;
            height: 50px;
            margin-left: 20px;
            text-align: center;
            font-size: 1.5em;
            border-left: 1px solid rgb(52, 50, 50);
            border-right: 1px solid rgb(52, 50, 50);
        }

        #userMatchProbabilityDv{
            float: left;
            width: 100px;
            height: 50px;
            margin-left: 10px;
            text-align: center;
            font-size: 1.5em;
            border-left: 1px solid rgb(52, 50, 50);
            border-right: 1px solid rgb(52, 50, 50);
        }

        #leaveButtonDv{
            width: 200px;
            height: 50px;
            margin: 150px auto 0;
            border: 1px solid red;
            text-align: center;
            font-size: 2em;
            cursor: pointer;
        }


        #userInformationRightFrame{
            position: absolute;
            width: 720px;
            height: 480px;
            padding-top: 10px;
            margin: 105px 0 0 350px;
            border-radius: 20px;
            background: white;
        }




        #pvpLayer{
            position: absolute;
            width: 100%;
            height: 100%;
            display: none;
        }

        #hideLayer{
            background-color: rgba(255,255,255,0.6);
            position: absolute;
            width: 100%;
            height: 100%;
            display: none;
            z-index: 10;
        }

        body{
            background: url("../img/pvp2.jpg");
            background-size:cover;
        }

        #start{
            background: url("../img/PK1.png");
            background-size:cover;
        }

        #leave{
            background: url("../img/PK2.png");
            background-size:cover;
        }

        body{margin: 0;padding: 0}
        button{outline: none;border: none}
    </style>
</head>
<body>
<div id="openLayer">
    <div id="openLayerContent">
        <div id="start">浏览玩家</div>
        <div id="leave">退出PK</div>
    </div>
</div>


<div id="userInformationLayer">
    <div id="userInformationLayerContent">
        <div id="userInformationLeftFrame">
            <div id="segmentPositionDv">
                <div id="segmentPositionNumberDv">
                    <b id="segmentPositionNumber"></b>
                    <b>胜点</b>
                </div>
                <div style="width: 75px;margin: 10px auto 0;border-top: 1px solid rgb(111, 108, 108);"></div>
                <div id="segmentPositionNameDv">
                    <b id="segmentPositionName"></b>
                </div>
            </div>
            <div id="userInformationDv" style="margin-top: 25px;">
                <div id="userMatchNumberDv">
                    <b>场数</b>
                    <p><b id="userMatchNumber"></b></p>
                </div>
                <div id="userMatchProbabilityDv">
                    <b>胜率</b>
                    <p><b id="userMatchProbability"></b><b>%</b></p>
                </div>
            </div>
            <div id="leaveButtonDv">
                <a href="user_index.html">退出PK</a>
            </div>
        </div>

        <div id="userInformationRightFrame">
            <div id="pvpTableDv">
                <table id="pvpTable"  lay-filter="pvpTable"></table>
            </div>
        </div>
    </div>

</div>


<div id="pvpLayer">

</div>

<div id="hideLayer"></div>

</body>

<script src="https://cdn.jsdelivr.net/npm/jquery" charset="utf-8"></script>
<script src="https://www.layuicdn.com/layui/layui.js" charset="utf-8"></script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-warm layui-btn-sm" lay-event="onLinePlayer" style="margin-left: 20px">在线用户</button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="applyListShow" style="margin-left: 20px">收到的申请</button>
        <span id="applyListShowNumeber" class="layui-badge" style="margin:-5px 0 0 -18px;position: absolute;border-radius: 100%">5</span>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="launchPlay">发起挑战</a>
</script>

<script type="text/html" id="barDemo1">
    <a class="layui-btn layui-btn-xs" style="background-color: #00a7de" lay-event="acceptPlay">接受挑战</a>
</script>

<script type="text/javascript">
    var tableType=null,enemyId;


    onLinePlayerShow();
    OpenShow();
    OpenSocket();

    $('#start').click(function () {
        $('#openLayer').css('display','none');
        $('#userInformationLayer').css('display','block');
    })

    $('#leave').click(function () {
        location.href='user_index.html'
    })




    function OpenShow(){
        $.ajax({
            url: '/pvp-info/myRecord/'+sessionStorage.getItem('userId'),
            method: 'GET',
            contentType: 'application/json',
            success: function (res) {
                $('#segmentPositionNumber').text(res.data.moreWinning)
                $('#segmentPositionName').text(res.data.level)
                $('#userMatchNumber').text(res.data.total)
                $('#userMatchProbability').text(res.data.winningRate)
            }
        })
    }


    function onLinePlayerShow() {
        layui.use(['table','element'], function () {
           var table = layui.table;

       table.render({
            elem: '#pvpTable'
           , height: 455
           , method: 'POST'
           ,url: '/pvp-info/allConnect'
           , contentType: "application/json"
           ,toolbar: '#toolbarDemo'
           ,defaultToolbar: false
           ,limit:6
           ,loading:true
           ,skin: 'line'
           ,even: true
           ,size: 'lg'
           , request: {
                pageName: 'displayStart'
               , limitName: 'displayLength'
           }
           , response: {
               statusCode: 200
           }
           ,where: {
               userId: sessionStorage.getItem('userId')
           }
           ,parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data.records
                }

            }
            , cols: [[
                 {field: 'userId', hide:true}
                ,{field: 'userName', title: '用户昵称', width: 170,align: 'center'}
                , {field: 'sex', title: '性别', width: 80,align: 'center'}
                , {field: 'win', title: '胜场', width: 120, align: 'center',sort: true}
                , {field: 'total', title: '比赛场数', width: 120, align: 'center',sort: true}
                , {field: 'winning', title: '总胜点', width: 100, align: 'center',sort: true}
                , {title:'操作', width: 120, align: 'center', toolbar: '#barDemo'}
            ]]
        });

            table.on('toolbar(pvpTable)', function(obj){
                switch(obj.event){
                    case 'onLinePlayer':
                        onLinePlayerShow()
                        break;
                    case 'applyListShow':
                        applyListShow()
                        break;
                };
            });


            table.on('tool(pvpTable)', function(obj){
                let enemyData = obj.data;
                if(obj.event === 'launchPlay'){
                    $.ajax({
                        url: '/pvp-info/chooseEnemy',
                        method: 'POST',
                        contentType: 'application/json',
                        data:JSON.stringify({
                            userId:sessionStorage.getItem('userId'),
                            enemyId:enemyData.userId
                        }),
                        success: function (res) {
                            if(res.code===400){
                                layer.msg(res.msg)
                            }
                            else if (res.code===200){
                                layer.msg('正在向'+enemyData.userName+'发起挑战');
                            }
                        }
                    })
                }
            });

        })
    }

    
    function applyListShow() {
        layui.use(['table','element'], function () {
            var table = layui.table;


            table.render({
                elem: '#pvpTable'
                , height: 455
                , method: 'post'
                , contentType: "application/json"
                ,toolbar: '#toolbarDemo'
                ,defaultToolbar: false
                ,page: true
                ,limit:6
                ,loading:true
                ,skin: 'line'
                ,even: true
                ,size: 'lg'
                , request: {
                pageName: 'displayStart'
                    , limitName: 'displayLength'
            }
            , response: {
                statusCode: 200
            }
            , parseData: function (res) {
                return {
                    "code": res.code,
                    "msg": res.msg,
                    "count": res.count,
                    "data": res.data.records
                }

            }
            , cols: [[
                    {field: 'userId',hide:true}
                ,{field: 'userName', title: '用户昵称', width: 170,align: 'center'}
                , {field: 'sex', title: '性别', width: 80,align: 'center'}
                , {field: 'commodityType', title: '段位', width: 120, align: 'center',sort: true}
                , {field: 'commodityStock', title: '比赛场数', width: 120, align: 'center',sort: true}
                , {field: 'saleVolume', title: '胜率', width: 100, align: 'center',sort: true}
                , {title:'操作', width: 120, align: 'center', toolbar: '#barDemo1'}
            ]]
            ,data:[{
                    userId:'66',userName:'qq5',sex:'男',commodityType:'ddd',commodityStock:'80',saleVolume:'sa'
            },{
                    userId:'99',userName:'qqs',sex:'男',commodityType:'ddd',commodityStock:'100',saleVolume:'sa'
            },{
                    userId:'123',userName:'dqqq',sex:'男',commodityType:'ddd',commodityStock:'32',saleVolume:'sa'
            },{
                    userId:'263',userName:'ddaa',sex:'男',commodityType:'ddd',commodityStock:'64',saleVolume:'sa'
            },{
                    userId:'213',userName:'22555d',sex:'男',commodityType:'ddd',commodityStock:'70',saleVolume:'sa'
            }]
        });

            table.on('toolbar(pvpTable)', function(obj){
                switch(obj.event){
                    case 'onLinePlayer':
                        onLinePlayerShow()
                        break;
                    case 'applyListShow':
                        applyListShow()
                        break;
                };
            });

            table.on('tool(pvpTable)', function(obj){
                let data = obj.data;
                if(obj.event === 'acceptPlay'){
                    $('#hideLayer').css('display','block')
                    layer.msg('已经同意'+data.userName+'的挑战，正在进入房间......请稍后', function(){
                        let newDate=sessionStorage.getItem('userId')+','+data.userId
                        socket.send("发送信息到后台"+"ws://localhost:8848/websocket/"+newDate);
                    });
                }
            });

        })
    }


    function OpenSocket() {
        socket = new WebSocket ( "ws://localhost:8848/websocket/"+sessionStorage.getItem('userId'));
        // 打开事件
        socket.onopen = function () {
            console.log ( "Socket 已打开 " );
        };

        // 获得消息事件
        socket.onmessage = function (msg) {
            let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
            if(reg.test(msg.data)){

                if (msg.data==='对方拒绝了你的挑战....'){
                    layer.msg(msg.data)
                }
                else {
                questionIds=JSON.parse(msg.data);
                let Data=JSON.parse(msg.data);
                sessionStorage.setItem('enemyId',Data.enemyID)
                    layer.msg('对方已同意PK请求，正在进入房间.....',function (){
                        location.href='pvp_index.html'
                    })

                }
            }
            else {
                $.ajax({
                    url: '/user/getUserInfoById/'+msg.data,
                    method: 'GET',
                    contentType: 'application/json',
                    success: function (res) {
                        enemyId=msg.data;
                        sessionStorage.setItem('enemyId',enemyId)
                        layer.msg('有一封来自玩家'+ res.data.username+'的挑战书！'
                            ,function () {
                                let confirm= layer.confirm('是否接受玩家'+ res.data.username+'的PK申请', {
                                        title:'PK对战申请',btn: ['接受','忽略'],resize:false
                                    }
                                    ,function (){
                                        $.ajax({
                                            url: '/pvp-info/myRequest',
                                            method: 'POST',
                                            contentType: 'application/json',
                                            data:JSON.stringify({
                                                userId:enemyId,
                                                enemyId:sessionStorage.getItem('userId'),
                                                choose:'y'
                                            }),
                                            success: function () {
                                                layer.msg('正在确认对战连接.....请稍后'
                                                    ,function (){
                                                        location.href='pvp_index.html'
                                                    })
                                            }
                                        })
                                        layer.close(confirm)
                                    }
                                    ,function(){
                                        $.ajax({
                                            url: '/pvp-info/myRequest',
                                            method: 'POST',
                                            contentType: 'application/json',
                                            data:JSON.stringify({
                                                userId:enemyId,
                                                enemyId:sessionStorage.getItem('userId'),
                                                choose:'n'
                                            })
                                        })
                                        layer.close(confirm)
                                    })

                            })
                    }})
            }
        };

// 发生了错误事件
        socket.onerror = function () {
            alert ( "Socket 发生了错误 " );
// 此时可以尝试刷新页面
        };
    }


</script>
</html>